02.03.07 点积(Dot Product)
我们已经学习了按元素操作、
求和及平均值。 另一个最基本的操作之一是点积。 给定两个向量
,
它们的点积
(dot product)

是相同位置的按元素乘积的和
:。
import torch
x = torch.arange(4).float() # 转为 float32
y = torch.ones(4, dtype = torch.float32)
print(x, y, torch.dot(x, y))
返回值:
tensor([0., 1., 2., 3.]) tensor([1., 1., 1., 1.]) tensor(6.)
注意, 我们可以通过执行按元素乘法,然后进行求和来表示两个向量的点积:
import torch
x = torch.arange(4).float() # 转为 float32
y = torch.ones(4, dtype = torch.float32)
B=torch.sum(x * y)
print(x, y)
print(B)
返回值:
tensor([0., 1., 2., 3.]) tensor([1., 1., 1., 1.])
tensor(6.)
点积在很多场合都很有用。
例如,给定一组由向量表示
的值,
和一组由
表示的权重。
X
中的值根据权重
W
的加权和,
可以表示为点积
。
当权重为非负数且和为1
时, 点积表示 加权平均 (weighted average)。 将两个向量规范化得到单位长度后,点积表示它们夹角的余弦。 本节后面的内容将正式介绍长度(length)的概念。